<script setup lang="ts">
import type { FormInstance, UploadProps } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';

import { computed, reactive, ref } from 'vue';

import { MdiCheck } from '@vben/icons';
import { useAccessStore } from '@vben/stores';
import { processHtmlContent } from '@vben/utils';

import { useMutation, useQuery } from '@tanstack/vue-query';
import {
  Button,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Upload,
} from 'ant-design-vue';

import { BriefAddTask, BriefDetail, BriefUpdateTask } from '#/api';

import '@vueup/vue-quill/dist/vue-quill.snow.css';

const emits = defineEmits<{
  success: [];
}>();

const visible = ref<boolean>(false);
const rowId = ref<number | undefined>(undefined);
const fileList = ref<any[]>([]);

const quillEditorRef = ref();

const { accessToken } = useAccessStore();

const formRef = ref<FormInstance>();
const formModel = reactive<{
  filURL: string | undefined;
  name: string | undefined;
  result: any;
  resultDesc: string | undefined;
}>({
  name: undefined,
  result: undefined,
  filURL: undefined,
  resultDesc: undefined,
});

const formRules = reactive<Record<string, Rule[]>>({
  name: [{ required: true, message: '请输入项目名称' }],
  resultDesc: [{ required: true, message: '请输入描述' }],
  result: [{ required: true, message: '请输入内容' }],
  filURL: [{ required: true, message: '请上传文件' }],
});

// 文件上传配置
const uploadProps: UploadProps = {
  name: 'file',
  multiple: false,
  accept: '.pdf,.doc,.docx,.txt',
  action: '/api/brief/uploadFile',
  headers: {
    authorization: accessToken as string,
  },
  beforeUpload: (file) => {
    const isValidSize = file.size / 1024 / 1024 < 100; // 限制100MB
    if (!isValidSize) {
      message.error('文件大小不能超过100MB');
    }
    return isValidSize;
  },
  onChange: (info: any) => {
    if (info.file?.response && info.file?.response?.data)
      formModel.filURL = info.file?.response?.data as string;
    fileList.value = info.fileList;
  },
};

// 开始AI质检
// const startAICheck = () => {
//   if (!selectedBrief.value) {
//     message.warning('请选择Brief项目');
//     return;
//   }
//   if (fileList.value.length === 0) {
//     message.warning('请上传KOL大纲文件');
//     return;
//   }

//   loading.value = true;
//   // 模拟AI质检过程
//   setTimeout(() => {
//     loading.value = false;
//     message.success('AI质检完成');
//     visible.value = false;
//   }, 3000);
// };

// #创建任务
const { mutate: mutateCreateTask, isPending: isCreatePending } = useMutation({
  mutationFn: BriefAddTask,
  onSuccess() {
    emits('success');
    message.success('创建成功');
    handleCancel();
  },
});

// #更新任务
const { mutate: mutateUpdateTask, isPending: isUpdatePending } = useMutation({
  mutationFn: BriefUpdateTask,
  onSuccess() {
    emits('success');
    message.success('更新成功');
    handleCancel();
  },
});

// #查询详情
useQuery({
  enabled: computed(() => Boolean(rowId.value)),
  queryKey: ['brief/detail', computed(() => rowId.value)],
  queryFn: () => BriefDetail({ id: rowId.value! }),
  refetchOnWindowFocus: false,
  select: (res) => {
    formModel.name = res?.name;
    formModel.result = processHtmlContent(res.result ?? '');
    formModel.resultDesc = res.result_desc;
    return res;
  },
});

async function handleSubmit() {
  const contents = quillEditorRef.value?.getContents();
  if (contents === '<p><br></p>') formModel.result = undefined;
  await formRef.value?.validate();

  if (!rowId.value) {
    mutateCreateTask({
      name: formModel.name as string,
      fileUrl: formModel.filURL as string,
    });

    return;
  }

  mutateUpdateTask({
    taskId: rowId.value,
    name: formModel.name as string,
    result: formModel.result,
    resultDesc: formModel.resultDesc,
  });
}

function handleCancel() {
  quillEditorRef.value?.setContents(undefined);
  rowId.value = undefined;

  formRef.value?.resetFields();
  formModel.name = undefined;
  formModel.result = undefined;
  formModel.resultDesc = undefined;

  visible.value = false;
}

function handleInput(e: Event) {
  const target = e.target as HTMLDivElement;
  formModel.result = target.innerHTML;
}

defineExpose({
  open(params?: { id: number }) {
    rowId.value = params?.id || undefined;
    visible.value = true;
  },
});
</script>

<template>
  <Modal
    v-model:open="visible"
    :mask-closable="false"
    :title="Boolean(rowId) ? '更新Brief文档' : '上传Brief文档'"
    :width="800"
    @cancel="handleCancel"
  >
    <!-- <pre
      class="w-full overflow-auto whitespace-pre-wrap rounded-lg bg-gray-100 p-2"
    >
      {{ formModel }}
      </pre
    > -->

    <Form ref="formRef" :model="formModel" :rules="formRules" layout="vertical">
      <FormItem v-if="!rowId" name="filURL">
        <Upload.Dragger v-bind="uploadProps" v-model:file-list="fileList">
          <img
            alt=""
            class="mx-auto my-4 block w-[200px]"
            src="/undraw_going-up_g8av.svg"
          />
          <p class="text-sm">拖拽文件到此处或点击上传</p>
        </Upload.Dragger>
        <div class="mt-2 text-xs text-gray-500">
          支持文件格式：PDF、DOC、DOCX、TXT，文件大小不超过100MB
        </div>
      </FormItem>

      <FormItem label="项目名称" name="name">
        <Input
          v-model:value="formModel.name"
          allow-clear
          class="w-[400px]"
          placeholder="请输入项目名称"
        />
      </FormItem>

      <FormItem label="项目描述" name="resultDesc">
        <Input.TextArea
          v-model:value="formModel.resultDesc"
          allow-clear
          class="w-[500px]"
          placeholder="请输入项目描述"
        />
      </FormItem>

      <FormItem v-if="Boolean(rowId)" label="提取结果" name="result">
        <div
          contenteditable
          @blur="handleInput"
          v-html="formModel.result"
        ></div>
        <!-- <QuillEditor
          ref="quillEditorRef"
          v-model:content="formModel.result"
          content-type="html"
          placeholder="请输入"
          theme="snow"
          toolbar="full"
        /> -->
      </FormItem>
    </Form>

    <template #footer>
      <!-- <Button
        :disabled="!selectedBrief || fileList.length === 0"
        :loading="loading"
        type="primary"
        @click="startAICheck"
      >
        <MdiBrain class="mr-2 inline-block" />
        {{ loading ? '正在进行AI质检...' : '开始AI质检' }}
      </Button> -->

      <Button
        :loading="isCreatePending || isUpdatePending"
        type="primary"
        @click="handleSubmit"
      >
        <MdiCheck class="mr-2 inline-block" />
        {{ Boolean(rowId) ? '确认更新' : '确认创建' }}
      </Button>
    </template>
  </Modal>
</template>
